package com.mq.rabbitmq.deadletter;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;

/**
 * Created by Administrator on 2017/8/3.
 */
public class DealLetetterReceive {

    /**
     * 自动应答无线重试
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public SimpleMessageListenerContainer messageContainer(@Qualifier("firstConnectionFactory") ConnectionFactory connectionFactory) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.addQueues(new Queue(DealLetterConfig.QUEUE_DEAD_TEST));
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(1);
        container.setConcurrentConsumers(1);
        //不手动确认模式，如果有异常，会算消费吗
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
        container.setMessageListener(new ChannelAwareMessageListener() {
            @Override
            public void onMessage(Message message, Channel channel) throws Exception {
                byte[] body = message.getBody();
                System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<DealLetetterReceive receive message ");
               // channel.basicRject(message.getMessageProperties().getDeliveryTag(), false, false);
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            }
        });
        return container;
    }
}
